import pandas as pd
import ast

# ============ 配置 ============
INPUT_FILE = r"D:\software\Desktop\Ollama_damo\cleaned_extracted_triples.xlsx"
OUTPUT_FILE = r"D:\software\Desktop\Ollama_damo\parsed_triples.xlsx"

# ============ 解析嵌套 triple ============
def parse_nested_triple(triple_str):
    """
    解析嵌套三元组：
    ("外层sub", 'triple', '("内层sub", "rel", "obj")')
    返回 (subject, relation, object)
    """
    try:
        outer_tuple = ast.literal_eval(triple_str)
        if len(outer_tuple) != 3:
            return None, None, None
        inner_str = outer_tuple[2]  # 内层字符串
        inner_tuple = ast.literal_eval(inner_str)
        if len(inner_tuple) != 3:
            return None, None, None
        return inner_tuple  # (subject, relation, object)
    except Exception:
        return None, None, None

# ============ 主程序 ============
def main():
    print("🚀 正在加载文件...")
    df = pd.read_excel(INPUT_FILE)

    if "triple" not in df.columns:
        print("❌ Excel 文件中缺少 'triple' 列")
        return

    records = []

    for idx, row in df.iterrows():
        triple_str = str(row["triple"])
        subj, rel, obj = parse_nested_triple(triple_str)
        if not subj or not rel or not obj:
            print(f"[SKIP] 第{idx+1}行无法解析: {triple_str[:80]}...")
            continue

        records.append({
            "subject": subj,
            "relation": rel,
            "object": obj
        })

    if records:
        out_df = pd.DataFrame(records)
        out_df.to_excel(OUTPUT_FILE, index=False)
        print(f"✅ 成功解析 {len(records)} 条三元组，保存至：{OUTPUT_FILE}")
    else:
        print("⚠️ 未生成任何结果。")

# ============ 启动 ============
if __name__ == "__main__":
    main()
